package NewTmas.Listeners;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 7/13/11
 * Time: 10:55 AM
 * To put the existing internal frames in a cascading orientation
 */
public class CascadeWindowStateListener implements ItemListener {
    JDesktopPane dtp;
    JCheckBoxMenuItem cascade;

    public CascadeWindowStateListener(JDesktopPane dtp, JCheckBoxMenuItem cascade) {

        this.dtp=dtp;
        this.cascade=cascade;

    }

    public void itemStateChanged(ItemEvent e)
    {


          if(cascade.isSelected())
          {  cascade(dtp);
          }
    }

    public void cascade( JDesktopPane desktopPane ) {
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if ( frames.length == 0) return;

        cascade(frames, desktopPane.getBounds(), 24);
    }

    private  void cascade( JInternalFrame[] frames, Rectangle dBounds, int separation ) {
        int margin = frames.length*separation + separation;
        int width = dBounds.width - margin;
        int height = dBounds.height - margin;
        for ( int i = 0; i < frames.length; i++) {
            frames[i].setBounds( separation + dBounds.x + i*separation,
                    separation + dBounds.y + i*separation,
                    frames[i].getWidth(), frames[i].getHeight());
        }
    }


}
